/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package obai.model.util;

import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Fernando Arena Varella
 * @version 1.0
 */
public class PathParser1 {

    public PathParser1(){

    }

    /**
     * Extract the name of the file given the path to that file.
     * (e.g. return "index.html" if the path param pointed to
     * "storage/mySite/index.html")
     * @param path  the String of the path to the file
     * @return  the name of the file
     */
    public static String extractFileName(String path){
        Pattern pattern = Pattern.compile("\\w+\\.\\w+");
        Matcher matcher = pattern.matcher(path);
        int fileIndex = path.length();
        if (matcher.find()){
            fileIndex = path.indexOf(matcher.group());
        }
        return path.substring(fileIndex, path.length());
    }
    /**
     * Extract the name of the file given the url to that file.
     * (e.g. return "index.html" if the url param pointed to
     * "http://www.mywebsite.com/index.html")
     * @param url  the URL of the file
     * @return  the name of the file
     */
    public static String extractFileName(URL url){
        Pattern protocol = Pattern.compile("\\w+://");
        Matcher matcher = protocol.matcher(url.toString());
        String actualPath = url.toString();
        String urlStr = url.toString();
        String siteStr = null;
        if (matcher.find()){
            siteStr = matcher.group();
            Pattern siteName = Pattern.compile("(\\w+\\.)*\\w+");
            Matcher siteNameExcluder = siteName.matcher(url.toString().substring(matcher.end()));
            urlStr = url.toString().substring(matcher.end());
            if (siteNameExcluder.find()){
                siteStr += siteNameExcluder.group();
                actualPath = urlStr.substring(siteNameExcluder.end());
            }
        }
        return extractFileName(actualPath);
    }

    /**
     * Get the actual path to a given file (it will exclude the name of the
     * file from the output). (e.g.  return "storage/mySite/" if the 
     * path param pointed to "storage/mySite/index.html")
     * @param path  the String of the path to the file
     * @return  the path to the file
     */
    public static String excludeFileName(String path){
        Pattern pattern = Pattern.compile("/?\\w+\\.\\w+");
        Matcher matcher = pattern.matcher(path);
        int fileIndex = path.length();
        String lastMatch = null;
        //find the name of the file
        while (matcher.find()){
            lastMatch = matcher.group();
        }
        if (lastMatch != null){
            //set the index of the name of the file
            //+ 1 >>> to include the slash at the end of the String
            fileIndex = path.indexOf(lastMatch) + 1;
            if (! lastMatch.startsWith("/"))
                fileIndex--;
            //fileIndex = (fileIndex == 1) ? 0 : fileIndex;
        }
//        System.out.println(path);
        return path.substring(0,fileIndex);
    }
    /**
      * Get the actual path to a given file (it will exclude the name of the
     * file from the output). (e.g.  return "http://www.mywebsite.com/" if the
     * url param pointed to "http://www.mywebsite.com/index.html")
     * @param url   the String of the path to the file
     * @return  the path to the file
     */
    public static String excludeFileName(URL url){
        StringBuilder sb = new StringBuilder();
        sb.append(url.getProtocol() + "://" + url.getHost());
        if ((url.getPort() != -1))
            sb.append(":" + url.getPort());
        sb.append(excludeFileName(url.getFile()));
        return sb.toString();
    }
//    public static String excludeFileName(URL url){
//        Pattern protocol = Pattern.compile("\\w+://");
//        Matcher matcher = protocol.matcher(url.toString());
//        String actualPath = url.toString();
//        String urlStr = url.toString();
//        String siteStr = null;
//        if (matcher.find()){
//            //if it found a protocol:
//            //excludes the name of the site
//            siteStr = matcher.group();
//            Pattern siteName = Pattern.compile("(\\w+\\.)*\\w+");
//            Matcher siteNameExcluder = siteName.matcher(url.toString().substring(matcher.end()));
//            urlStr = url.toString().substring(matcher.end());
//            if (siteNameExcluder.find()){
//                siteStr += siteNameExcluder.group();
//                actualPath = urlStr.substring(siteNameExcluder.end());
//            }
//        }
//        //passes only the actual path to the another method
//        return siteStr + excludeFileName(actualPath);
//    }

    /**
     * Return the extension of the given file
     * @param fileName  the String of the name of the file
     * @return  the extension of the file
     */
    public static String getFileExtension(String fileName){
        Pattern pattern = Pattern.compile("\\.\\w+");
        Matcher matcher = pattern.matcher(fileName);
        int extIndex = 1;
        if (matcher.find()) {
            extIndex = fileName.indexOf(matcher.group()) + 1;   // >> + 1 to pass the dot
        }
        return fileName.substring(extIndex, fileName.length());
    }

    /**
     * Change the extension of a file (e.g. renames "index.jsp" to "index.html")
     * @param fileName      the name of the file
     * @param newExtension  the new extension (without the dot)
     * @return  the file name with the new extension
     */
    public static String changeFileExtensionTo(String fileName, String newExtension){
        Pattern pattern = Pattern.compile("\\.\\w+");
        Matcher matcher = pattern.matcher(fileName);
        int extIndex = 1;
        if (matcher.find()) {
            extIndex = fileName.indexOf(matcher.group()) + 1;   // >> + 1 to pass the dot
        }
        String newName = fileName.substring(0, extIndex);
        return newName + newExtension;
    }

    /**
     * Calculates if the path contains a file at it's end (e.g. return TRUE if 
     * the path param is "storage/mywebsite/index.html", return FALSE if
     * the path param is "storage/mywebsite/"
     * @param path  the String of the path
     * @return  true or false
     */
    public static boolean pathContainsFile(String path){
        Pattern pattern = Pattern.compile("/\\w+\\.\\w+|\\w+");
        Matcher matcher = pattern.matcher(path);
        if (matcher.find()){
            return true;
        }
        return false;
    }
    /**
     * Calculates if the path contains a file at it's end (e.g. return TRUE if
     * the url param is "http://www.mywebsite.com/index.html", return FALSE if
     * the url param is "http://www.mywebsite.com"
     * @param url   the URL
     * @return  true or false
     */
    public static boolean pathContainsFile(URL url){
        return pathContainsFile(url.getPath());
    }

    /**
     * Removes the directories that must be ommited becouse of the appearance of "../"
     * on the path String (i.e. will transform "dir1/dir2/../page.html" to
     * "dir1/page.html". It will also ignore any directory that is in the ignoreList
     * @param path  the String of the path
     * @param ignoreList the list of directories that cannot be excluded from
     * the path (it's a case for a very special application)
     * @return  the fixed String of the path
     */
    public static String fixBackwardsDirectories(String path, String... ignoreList) {
        Pattern pattern = Pattern.compile("\\w+/|\\.\\./");
        Matcher matcher = pattern.matcher(PathParser1.excludeFileName(path));
        ArrayList<String> dirs = new ArrayList<String>();
        while (matcher.find()){
            String group = matcher.group();
            if (group.equals("../")){
                //remove the last directorie unless it's in ignoreList
                int i = dirs.size()-1;
                //make sure it wont remove something that is in the ignoreList
                for (String s : ignoreList){
                    if (i < 0)
                        break;
                    if (dirs.get(i).equals(s + "/")){
                        System.out.println("S: " + s);
                        i--;
                    }
                }
                if (i >= 0)
                    dirs.remove(i); // >>> +1 to fix the postInc after the loop
            } else
                dirs.add(group);
        }

        String finalPath = "";
         //trick to catch the first "/"
        if (path.startsWith("/"))
            finalPath += "/";
        for (String dir : dirs)
            finalPath += dir;

        return finalPath + PathParser1.extractFileName(path);
    }



}
